package security.handler;/**
 * @Auther: liyipeng
 * @Date: 2020/1/9 14:40
 * @Description:
 */

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import security.SecurityUtil.login.CustomUserDetailService;
import util.Object2JsonString2ObjectUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>类名: JsonLoginSuccessHandler</p>
 * <p>描述:TODO</p>
 * <p>创建人: liyp</p>
 * <p>创建时间: 2020/1/9 14:40</p>
 * <p>@version 2.0  </p>
 * <p>修改内容: ......</p>
 * <p>修改说明: ......</p>
 * <p>修改时间: ......</p>
 * <p>修改人: ......</p>
 * <p>每次修改，请增加上述修改信息说明</>
 */
@Component
public class JsonLoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    CustomUserDetailService customUserDetailService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
        Map<String, Object> paramMap = new HashMap<>();
        Object principal = authentication.getPrincipal();
        if (!(principal instanceof UserDetails)) {
            paramMap.put("code", "101");
            paramMap.put("message", "登录成功!");
        }else {
            String token = customUserDetailService.createToken((UserDetails) principal);
            httpServletResponse.setHeader("Authorization", token);
            paramMap.put("code", "200");
            paramMap.put("message", "登录成功!");
            paramMap.put("token", token);
            //设置返回请求头
            httpServletResponse.setContentType("application/json;charset=utf-8");
        }
        //写出流
        PrintWriter out = httpServletResponse.getWriter();
        out.write(Object2JsonString2ObjectUtil.Object2JsonString(paramMap));
        out.flush();
        out.close();
    }
}
